package com.dz.lm.web.controller.pay;

import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.utils.XmlResolve;
import com.dz.lm.service.pay.WxPayService;
import com.dz.lm.web.controller.BasicControl;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付回调
 * 
 * @author zhanghairong
 */
@Controller
@RequestMapping("/rewriteUrl/callback")
public class WxPayCallBackControl extends BasicControl{
	
	public Logger logger = LogManager.getLogger(WxPayCallBackControl.class);
    
	@Autowired
    private WxPayService wxPayService;
    
    /**
     * 支付结果回调
     * 
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/{orderId}/wxPayCallback")
    public String wxPayCallback(HttpServletRequest request) throws ServiceException {
		System.out.println("进入微信回调=========================================");
    	Object orderId = request.getAttribute("orderId");
		System.out.println("进入微信回调========================================="+orderId);

		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> return_Data = new HashMap<String, Object>();
		param.put("orderId", orderId);
		System.out.println();
		StringBuffer info = new StringBuffer();
		InputStream in;
		try {
			in = request.getInputStream();
			BufferedInputStream buf = new BufferedInputStream(in);
			byte[] buffer = new byte[1024];
			int iRead;
			while ((iRead = buf.read(buffer)) != -1) {
				info.append(new String(buffer, 0, iRead, "UTF-8"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(info != null && info.length() > 0) {
			logger.info("微信支付回调请求参数：" + info);
			Map<String, Object> reqData = XmlResolve.callXMLToMap(info.toString());
			if (orderId != null && !orderId.equals(reqData.get("out_trade_no"))) {
				logger.error("订单号不匹配支付结果通知失败！");
				return_Data.put("return_code", "FAIL");
				return_Data.put("return_msg", "PARAMETER ERROR");
				return XmlResolve.callMapToXML(return_Data);
			} else {
				return_Data = wxPayService.wxPayCallback(reqData);
			}
		} else {
			logger.error("请求参数为空");
			return_Data.put("return_code", "FAIL");
			return_Data.put("return_msg", "PARAMETER ERROR");
		}
		return XmlResolve.callMapToXML(return_Data);
    }
}
